package io.mft.runtime.config.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import io.mft.commons.config.ConfigProvider;
import io.mft.commons.exception.MFTException;
import io.mft.dev.base.ApiThreadExecutorConfig;
import io.mft.runtime.config.ConfigLoader;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ApplicationConfigApiThreadExecutorLoader implements ConfigLoader<List<ApiThreadExecutorConfig>> {

	@Override
	public List<ApiThreadExecutorConfig> load(String appId) {
		List<ApiThreadExecutorConfig> list=new ArrayList<ApiThreadExecutorConfig>();
		try {
			List<ClassLoader> classLoaders=ConfigProvider.getConfigClassLoaders();
			Map<String, ApiThreadExecutorConfig> apiThreadExecutorConfigMap=new HashMap<String, ApiThreadExecutorConfig>();
			Map<String, ClassLoader> classLoaderMap=new HashMap<String, ClassLoader>();
			classLoaders.forEach(classLoader->{
				try {
					Map<String, Object> map=ConfigProvider.getNamespaceConfigObject(classLoader,"apiThreadExecutor");
					if (map!=null) {
						map.keySet().forEach(threadExecutorId->{
							try {
								Map<String, Object> configKv=ConfigProvider.getMapValue(map,threadExecutorId);
								ApiThreadExecutorConfig config=BeanUtil.toBean(configKv, ApiThreadExecutorConfig.class);
								if (apiThreadExecutorConfigMap.containsKey(threadExecutorId)) {
									StringBuilder msg=new StringBuilder();
									msg.append("当前apiThreadExecutor["+threadExecutorId+"]归属应用目录["+classLoader.getResource(".").getPath()+"]系统["+config.getSystemKey()+"]模块["+config.getModuleKey()+"]");
									msg.append("存在于应用目录["+classLoaderMap.get(threadExecutorId).getResource(".").getPath()+"]系统模块["+apiThreadExecutorConfigMap.get(threadExecutorId).threadExecutorId()+"]");
									throw new MFTException(msg.toString());
								}
								apiThreadExecutorConfigMap.put(threadExecutorId, config);
								classLoaderMap.put(threadExecutorId, classLoader);
							} catch (MFTException e) {
								log.error("",e);
							}catch (Exception e) {
								log.error("应用插件["+classLoader.getResource(".").getPath()+"]apiThreadExecutor配置解析异常",e);
							}
						});
					}

				} catch (Exception e) {
					log.error("应用插件["+classLoader.getResource(".").getPath()+"]接口apiThreadExecutor解析异常",e);
				}
			});
			list.addAll(apiThreadExecutorConfigMap.values());
		} catch (Exception e) {
			log.error("",e);
		}
		return list;
	}
}
